package com.nanhang.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nanhang.common.util.PageResult;
import com.nanhang.entity.Classes;
import com.nanhang.entity.Student;
import com.nanhang.mapper.StudentMapper;
import com.nanhang.service.IClassesService;
import com.nanhang.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanhang.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

	@Autowired
	private IClassesService classesService;

	@Override
	public PageResult<Student> findByPage(Integer page, Integer pageSize) {
		Page<Student> studentPage = this.page(new Page<>(page, pageSize));

		return new PageResult<>(studentPage.getRecords(), studentPage.getTotal());
	}

	@Override
	public PageResult<Student> search(Integer page, Integer pageSize, StudentVO vo) {
		QueryWrapper<Student> queryWrapper = new QueryWrapper<>();

		if (StrUtil.isNotBlank(vo.getSname())) {
			queryWrapper.like("sname", vo.getSname());
		}

		if (StrUtil.isNotBlank(vo.getAddr())) {
			queryWrapper.like("addr", vo.getAddr());
		}

		if (vo.getCid()!= null && vo.getCid()!= 0) {
			queryWrapper.eq("cid", vo.getCid());
		}

		Page<Student> studentPage = this.page(new Page<>(page, pageSize), queryWrapper);

		studentPage.getRecords().forEach(student -> {
			Classes classes = classesService.getById(student.getCid());
			if (classes!= null) {
				student.setCname(classes.getCname());
			}
		});

		return new PageResult<>(studentPage.getRecords(), studentPage.getTotal());
	}

	@Override
	public boolean add(Student student) {
		return this.save(student);
	}
}


